package com.itheima.controller1;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import com.itheima.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

/**
 * 体检预约
 * Author chongge
 * Time 2019/10/29 19:54
 * ClassName com.itheima.controller1
 */
@RestController
@RequestMapping(value = "/order")
public class OrderController {
    @Autowired
    private JedisPool jedisPool;

    @Reference
    private OrderService orderService;


    /***
     * 提交预约数据
     * @param map
     * @return
     */
    @RequestMapping(value = "submit",method = RequestMethod.POST)
    public Result submitOrder(@RequestBody Map map){

        try {
            //1.判断验证码是否正确
            String validateCode = (String) map.get("validateCode");
            String telephone = (String) map.get("telephone");
            String orderDate = (String) map.get("orderDate");
            String code = jedisPool.getResource().get(RedisMessageConstant.SENDTYPE_ORDER + "_" + telephone);
            if (StringUtils.isEmpty(validateCode) || StringUtils.isEmpty(code) || !code.equals(validateCode)) {
                return new Result(false, MessageConstant.VALIDATECODE_ERROR);
            }
            map.put("orderType","微信预约");
            //2.调用业务层进行体检预约
            Result result = orderService.submitOrder(map);
            //3.发送短信通知
            //预约失败
            if (!result.isFlag()){
                return new Result(false,result.getMessage());
            }
            //成功发送短信
            SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE,telephone,orderDate);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("我也不知道哪里错了");
        }
    }

    /***
     * 根据id查询预约信息
     * @param id
     * @return
     */
    @RequestMapping(value = "/findById",method = RequestMethod.POST)
    public Result findById(Integer id){
        Result result = null;
        try {
            result = orderService.findById(id);
            return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,result.getData());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }

    }

}
